package org.jsola.hr.web;

import org.apache.commons.io.FilenameUtils;
import org.jsola.common.FileKit;
import org.jsola.contract.query.AppendixQuery;
import org.jsola.contract.vo.AppendixListVO;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.*;
import org.jsola.hr.entity.EmpContractDO;
import org.jsola.hr.exception.HrException;
import org.jsola.hr.provider.IContractProviderService;
import org.jsola.hr.query.EmpContractQuery;
import org.jsola.hr.query.HrContractQuery;
import org.jsola.hr.service.IEmpContractService;
import org.jsola.hr.service.IHrPermissionService;
import org.jsola.hr.vo.*;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;


/**
 * 员工合同信息
 *
 * @author zhr
 */
@RestController("hrEmpContractController")
@RequestMapping(HrConstants.API_PATH + "/v1/empContracts")
public class EmpContractController implements IEmpContractControllerAPI {

    @Autowired
    private IHrPermissionService hrPermissionService;

    @Autowired
    private IEmpContractService empContractService;

    @Autowired
    private IContractProviderService contractProviderService;

    @Override
    @PostMapping
    public Result<EmpContractVO> save(@Valid @RequestBody EmpContractAddDTO empContractAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增员工合同信息权限校验

        return Result.success(
                empContractService.save(empContractAddDTO, tokenUser)
        );
    }


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody EmpContractUpdateDTO empContractUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改员工合同信息权限校验

        int count = empContractService.update(empContractUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }


    @Override
    @PostMapping(value = "/batch")
    public Result batch(@Valid @RequestBody EmpContractBatchDTO empContractBatchDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量操作权限校验

        // 批量操作，注意校验，有越权风险
        // 新增
        List<EmpContractAddDTO> empContractAddDTOList = empContractBatchDTO.getEmpContractAddDTOList();
        if (!CollectionUtils.isEmpty(empContractAddDTOList)) {
            empContractService.batchSave(empContractAddDTOList, tokenUser);
        }
        // 修改
        List<EmpContractUpdateDTO> empContractUpdateDTOList = empContractBatchDTO.getEmpContractUpdateDTOList();
        if (!CollectionUtils.isEmpty(empContractUpdateDTOList)) {
            empContractUpdateDTOList.parallelStream().forEach(
                    empContractUpdateDTO -> {
                        empContractService.update(empContractUpdateDTO, tokenUser);
                    }
            );
        }
        // 删除
        List<String> deleteEmpContractIdList = empContractBatchDTO.getDeleteEmpContractIdList();
        if (!CollectionUtils.isEmpty(deleteEmpContractIdList)) {
            empContractService.deleteByIds(tokenUser, deleteEmpContractIdList.toArray(new String[0]));
        }
        return Result.success();
    }


    @Override
    @DeleteMapping(value = "/{empContractId}")
    public Result<Integer> delete(@PathVariable String empContractId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除员工合同信息权限校验

        int count = empContractService.deleteByIds(tokenUser, empContractId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody String[] empContractIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除员工合同信息权限校验

        int count = empContractService.deleteByIds(tokenUser, empContractIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping(value = "/{empContractId}")
    public Result<EmpContractVO> findById(@PathVariable String empContractId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看员工合同信息权限校验

        return Result.success(
                empContractService.selectById(empContractId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<EmpContractListVO>> listAll(@Valid EmpContractQuery empContractQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看员工合同信息权限校验

        return Result.success(
                empContractService.select(empContractQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping
    public Result<Page<EmpContractListVO>> page(@Valid EmpContractQuery empContractQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empContractService.selectPage(empContractQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @PostMapping("/publishTemplateSign")
    public Result<String> publishTemplateSign(@Valid @RequestBody HrPublishSignDTO hrPublishSignDTO) {
        TokenUser tokenUser = UserContext.getUser();
        contractProviderService.publishTemplateSign(hrPublishSignDTO, tokenUser);
        return Result.success();
    }

    @Override
    @GetMapping("/selectContractPage")
    public Result<Page<HrContractListVO>> selectContractPage(HrContractQuery hrContractQuery) {
        TokenUser tokenUser = UserContext.getUser();
        return Result.success(
                contractProviderService.selectContractPage(hrContractQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @PostMapping("/selectContractPagePost")
    public Result<Page<HrContractListVO>> selectContractPagePost(@RequestBody HrContractQuery hrContractQuery) {
        TokenUser tokenUser = UserContext.getUser();

//        PermissionException.isTrue(hrPermissionService.hasRight(tokenUser.getUserId(), tokenUser.getSiteId(),
//                HR_ENTERPRISEOVERVIEW_CONTRACT), PERMISSION_DENIED_MESSAGE);

        return Result.success(
                contractProviderService.selectContractPage(hrContractQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping(value = "/selectAppendix")
    public Result<List<AppendixListVO>> selectAppendix(@Valid AppendixQuery appendixQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看合同文件权限校验

        return Result.success(
                contractProviderService.selectAppendix(appendixQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @PostMapping("/sendContractCode")
    public Result<Boolean> sendContractCode() {

        TokenUser tokenUser = UserContext.getUser();
        return contractProviderService.sendContractCode(tokenUser);

    }

    @Override
    @PostMapping("/importFile")
    public Result<EmpContractExcelVO> importFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam("companyId") String companyId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 导入excel权限校验

        // 临时保存到本地
        String excelFilePath = FileKit.saveFileToLocal(file, null, null, new String[]{"xls", "xlsx"}, null);
        File excelFile = new File(excelFilePath);
        HrException.isTrue(excelFile.exists(), "文件上传失败");

        EmpContractExcelVO empContractExcelVO = empContractService.importFile(excelFile, tokenUser, companyId);
        if (Objects.isNull(empContractExcelVO)) {
            return Result.fail("文件上传失败,请检查上传的模板");
        }

        return Result.success(empContractExcelVO);
    }

    @Override
    @GetMapping(value = "/listByType")
    public Result<EmpContractVO> listByType(@Valid String empId, String type) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看合同文件权限校验

        List<EmpContractDO> empContractDOList = empContractService.listByType(empId, type, tokenUser.getSiteId());
        if (CollectionUtils.isEmpty(empContractDOList)) {
            return Result.success();
        }
        return Result.success(
                empContractDOList.get(0).to(EmpContractVO.class)
        );
    }

    @Override
    @GetMapping(value = "/pageElectronicAndPaper")
    public Result<Page<HrContractVO>> pageElectronicAndPaper(@Valid EmpContractQuery empContractQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empContractService.pageElectronicAndPaper(empContractQuery, tokenUser)
        );
    }

    @Override
    @PostMapping(value = "/pageElectronicAndPaperPost")
    public Result<Page<HrContractVO>> pageElectronicAndPaperPost(@Valid @RequestBody EmpContractQuery empContractQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empContractService.pageElectronicAndPaper(empContractQuery, tokenUser)
        );
    }

    @Override
    @PostMapping(value = "/pageElectronicAndPaperForXcx")
    public Result<Page<HrContractVO>> pageElectronicAndPaperForXcx(@Valid @RequestBody EmpContractQuery empContractQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empContractService.pageElectronicAndPaperForXcx(empContractQuery, tokenUser)
        );
    }


    @Override
    @GetMapping(value = "/selectElectronicAndPaperNumber")
    public Result<HrContractCountVO> selectElectronicAndPaperNumber(@Valid EmpContractQuery empContractQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empContractService.selectElectronicAndPaperNumber(empContractQuery, tokenUser)
        );
    }

    @Override
    @PostMapping(value = "/selectElectronicAndPaperNumberPost")
    public Result<HrContractCountVO> selectElectronicAndPaperNumberPost(@Valid @RequestBody EmpContractQuery empContractQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                empContractService.selectElectronicAndPaperNumber(empContractQuery, tokenUser)
        );
    }

    @Override
    @PostMapping("/exportAllContract")
    public ResponseEntity<Resource> exportAllContract(@RequestBody EmpContractQuery empContractQuery) {
        TokenUser tokenUser = UserContext.getUser();

        empContractQuery.setEnName("contract");
        // todo 查看项目权限校验
        String excelFilePath = empContractService.exportAllContract(empContractQuery, tokenUser);
        // 导出excel
        // 编码文件名，防止乱码
        String filenames = new String(FilenameUtils.getName(excelFilePath).getBytes(StandardCharsets.UTF_8),
                StandardCharsets.ISO_8859_1);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel")
                .body(new FileSystemResource(excelFilePath));
    }

    @Override
    @DeleteMapping("/deleteBatchElectronicAndPaperNumber")
    public Result<Integer> deleteBatchElectronicAndPaperNumber(@RequestBody @Valid EmpAllContractDeleteDTO[] empAllContractDeleteDTOS) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除员工合同信息权限校验

        int count = empContractService.deleteBatchElectronicAndPaperNumber(empAllContractDeleteDTOS, tokenUser);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

}

